//
//  LoginManager.m
//  TTFriend
//
//  Created by 李正兵 on 2019/5/6.
//  Copyright © 2019 李正兵. All rights reserved.
//

#import "LoginManager.h"

NSString *const kUserLoginState = @"kUserLoginState";
NSString *const kUserLoginAccount = @"kUserLoginAccount";

@interface LoginManager()

@property (nonatomic, assign, readwrite)BOOL islogined;

@property (nonatomic, copy, readwrite)NSString * userAccount;

@property (nonatomic, copy)NSString * passWord;

@property (nonatomic, strong)NSDictionary * acountPairs;

@end

@implementation LoginManager

- (instancetype)init {
    self = [super init];
    if (self) {
        _acountPairs = @{@"ttfriend":@"123456",@"13122732267":@"123456",@"admin":@"111111"};
        _islogined = [[NSUserDefaults standardUserDefaults] boolForKey:kUserLoginState];
        _userAccount = [[NSUserDefaults standardUserDefaults] objectForKey:kUserLoginAccount];
    }
    return self;
}
+ (instancetype)shareManager {
    static LoginManager *shareManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareManager = [[self alloc] init];
    });
    return shareManager;
}
- (void)login:(NSString *)userAccount password:(NSString *)password completion:(void (^)(BOOL))completion {
    BOOL isvaild = NO;
    
    if (userAccount && userAccount.length) {
        if (self.acountPairs[userAccount] && [self.acountPairs[userAccount] isEqualToString:password] ) {
            isvaild = YES;
        }
    }

    self.userAccount = isvaild?userAccount:nil;
    self.passWord = isvaild?password: nil;
    self.islogined = isvaild;
    
    [[NSUserDefaults standardUserDefaults] setBool:isvaild forKey:kUserLoginState];
    [[NSUserDefaults standardUserDefaults] setObject:userAccount forKey:kUserLoginAccount];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (completion) {
        completion(isvaild);
    }
}

- (void)logoutWithCompletion:(void (^)(void))completion {
    self.userAccount = nil;
    self.passWord = nil;
    self.islogined = NO;
    
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:kUserLoginState];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kUserLoginAccount];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (completion) {
        completion();
    }
}
@end
